<?php


namespace App\Service\College;

use App\Models\College\CollegeCourseModel;
use Exception;
use App\Models\College\CollegeCategoryModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class CategoryService
{


    /**
     * 获取分类列表
     * @return mixed
     */
    public static function getCategoryList()
    {
        return CollegeCategoryModel::getList();
    }

    /**
     * 添加分类
     * @param $request
     * @throws Exception
     */
    public static function addCategory($request)
    {
        try {
            $data = [
                'name' => $request->name,
                'sort' => $request->sort,
            ];
            CollegeCategoryModel::addCategory($data);
        } catch (Exception $e) {
            handleException($e);
        }
    }

    /**
     * 修改分类
     * @param $request
     * @throws Exception
     */
    public static function updateCategory($request)
    {
        try {
            $data = [
                'name' => $request->name,
                'sort' => $request->sort,
            ];
            CollegeCategoryModel::setCategoryInfoById($request->id, $data);
        } catch (Exception $e) {
            handleException($e);
        }
    }

    /**
     * get info
     * @param $request
     * @return Builder|Model|object|null
     */
    public static function getCategoryInfo($request)
    {
        return CollegeCategoryModel::getCategoryInfoById($request->id);
    }


    /**
     * 删除分类
     * @param $request
     * @return mixed|void
     */
    public static function deleteCategory($request)
    {
        //查询分类下课程数量
        $coursesCount = CollegeCourseModel::query()
            ->where('categoryId', $request->id)
            ->count();

        if ($coursesCount > 0) {
            return $coursesCount;
        }
        CollegeCategoryModel::setCategoryInfoById($request->id, [
            'isDeleted' => 1
        ]);
        return 0;
    }


}
